package org.chnxi.study.nio.netty.groupchat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NioGroupChatClient {

    private final String host;

    private final int port;

    NioGroupChatClient(String host , int port){
        this.host = host;
        this.port = port;
    }

    NioEventLoopGroup workerGroup;

    Bootstrap bootstrap;

    public void run(){

        try{
            bootstrap = new Bootstrap();
            workerGroup = new NioEventLoopGroup();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("StringEncoder" , new StringEncoder());
                            socketChannel.pipeline().addLast("StringDecoder" , new StringDecoder());
                            socketChannel.pipeline().addLast("ChatHandler" , new NioGroupChatClientHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect(host, port).sync();

            Channel channel = future.channel();

            System.out.println("=========="+channel.localAddress()+"==========");

            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }

        }catch (Exception e){
            e.printStackTrace();
            System.exit(-1);
        }finally {
            workerGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        NioGroupChatClient client = new NioGroupChatClient("127.0.0.1", 6666);
        client.run();
    }

}
